import configs from '@/config/index'
import errorCode from '@/config/errorCode'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import {
	getCode
} from '@/api/index.js'
let timeout = 10000
const baseUrl = configs.baseUrl
// let isRefreshing = true;
// let subscribers = [];

// function onAccessTokenFetched() {
// 	subscribers.forEach((callback) => {
// 		callback();
// 	})
// 	subscribers = [];
// }

// function addSubscriber(callback) {
// 	subscribers.push(callback)
// }
const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.header || {}
	const token = uni.getStorageSync('userToken') || ''
	if (token && !isToken) {
		config.header['token'] = token
	}
	// console.log(config.header);
	// config.header['Authorization'] = 'Bearer ' + 'eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjE1NWM0Yjg1LWZiYWItNDUwMi1hNTMwLTk3NDdkNDFjZWI4NSJ9.uliCSeY-5C1eUDVnKpbSqm2rQdqiB26z3to1QN-u5bObhybVfsNADYsf4UzYrwf2YnA47a4Hrvx_JLg-NIJU0w'
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	return new Promise((resolve, reject) => {
		uni.request({
			method: config.method || 'get',
			timeout: config.timeout || timeout,
			url: config.baseUrl || baseUrl + config.url,
			data: config.data,
			header: config.header,
			dataType: 'json'
		}).then(response => {
			console.log(response, 'responseresponse')
			const errMsg = response.errMsg
			const statusCode = response.statusCode
			const data = response.data
			if (data.status === 404) {
				toast(data.status + data.error)
				reject(data.status)
				return
			}
			if (statusCode !== 200) {
				toast(errMsg)
				reject(statusCode)
				return
			}
			const code = data.ret || data.code || data.status || 200
			const msg = data.msg || data.message || errorCode[code] || errorCode['default'] || data
				.error
			if (code === 401) {
				showConfirm('会话已过期，请重新登录').then(res => {
					if (res.confirm) {
						console.log('点击确认/重新登录')
					}
				})
				reject('无效的会话，或者会话已过期，请重新登录。')
			} else if (code === 10002) {
				uni.navigateTo({
					url: '/pages/index/index'
				})
			} else if (code === 500) {
				// 将需要重新执行的接口缓存到一个队列中
				// if (msg == 'token已过期.') {
				// 	addSubscriber(() => {
				// 		request({
				// 			method: config.method || 'get',
				// 			timeout: config.timeout || timeout,
				// 			url: config.baseUrl || config.url,
				// 			data: config.data,
				// 			header: config.header,
				// 			dataType: 'json',
				// 			callback: resolve
				// 		})
				// 	})
				// 	if (isRefreshing) {
				// 		getCode().then(res => {
				// 			// 依次去执行缓存的接口
				// 			onAccessTokenFetched();
				// 			isRefreshing = true;
				// 		})
				// 	}
				// 	isRefreshing = false;
				// }
				if(msg!='token已过期.'){
					toast(msg)
				}
				reject(msg)
			} else if (code !== 200) {
				toast(msg)
				reject(code)
			}
			if (code === 200) {
				const resData = (data.status && data.status === 'creating') ? 'creating' : (!data
					.data) ? data : data.data
				resolve(resData)
			} else {
				if(msg!='token已过期.'){
					toast(msg)
				}
				reject(code)
			}
		}).catch(error => {
			let {
				message
			} = error
			if (message === 'Network Error') {
				message = '后端接口连接异常'
			} else if (message.includes('timeout')) {
				message = '系统接口请求超时'
			} else if (message.includes('Request failed with status code')) {
				message = '系统接口' + message.substr(message.length - 3) + '异常'
			}
			toast(message)
			reject(error)
		})
	})
}
export default request